package run.halo.app.event.bark;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import run.halo.app.config.properties.BarkProperties;
import run.halo.app.model.params.BarkParam;

import javax.annotation.Resource;

/**
 * @author yangxin
 * @date 2019/12/13
 */
@Component
@Slf4j
public class BarkEventListener {

    @Resource
    private BarkProperties barkProperties;

    @EventListener
    @Async
    public void onApplicationEvent(BarkEvent event) {
        BarkParam barkParam = event.getBarkParam();
        if (StringUtils.isBlank(barkProperties.getUrl())) {
            log.error("bark url is empty");
            return;
        }
        if (StringUtils.isBlank(barkProperties.getKey())) {
            log.error("bark key is empty");
            return;
        }
        StringBuilder sb = new StringBuilder(barkProperties.getUrl()).append(barkProperties.getKey());
        if (StringUtils.isNotBlank(barkParam.getTitle())) {
            sb.append("/").append(barkParam.getTitle());
        }
        if (StringUtils.isNotBlank(barkParam.getBody())) {
            sb.append("/").append(barkParam.getBody());
        }
        log.info("==============  push bark. request url: {} ==============", sb.toString());
        HttpResponse response = HttpUtil.createGet(sb.toString()).execute();
        log.info("===========  bark push result :{} ===========", response.body());
    }

}